﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;

namespace System.ComponentModel.DataAnnotations
{
    public class ByteLengthAttribute : StringLengthAttribute
    {
        public ByteLengthAttribute(int maximumLength)
            : base(maximumLength)
        {
        }

        public override bool IsValid(object value)
        {
            string input = value == null ? string.Empty : value.ToString();

            int length = input.Length,
                index = 0,
                charCount = 0;
            while (index < length)
            {
                if (input[index] > 255) charCount += 2;
                else charCount++;
                index++;
            }

            return charCount <= MaximumLength;
        }
    }
}
